package org.wei.utils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import net.iharder.Base64;

public class StringUtil {

	public static boolean isNumbers(String string) {
		if (string == null) {
			return false;
		}
		return string.matches("[0-9]+");
	}

	public static boolean mobileNumbers(String string) {
		if (string == null) {
			return false;
		}
		return string.matches("[0-9]{11}");
	}

	public static String randomString(int length) {
		return randomString("abcdefghijklmnopqrstuvwxyz0123456789", length);
	}

	public static String randomNumbers(int length) {
		return randomString("0123456789", length);
	}

	public static String randomString(String base, int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String extensionByFileName(String fileName) {
		int lastDotIndex = fileName.lastIndexOf(".");
		String extension = fileName.substring(lastDotIndex).replace(".", "");
		return extension;
	}

	public static boolean isEmptyString(String str) {
		if (str == null || str.isEmpty()) {
			return true;
		}
		return false;
	}

	public static List<Integer> parseStr2List(String arrayString) {
		List<Integer> result = new ArrayList<Integer>();
		if (arrayString == null || arrayString.equals("[]")) {
			return result;
		}
		arrayString = arrayString.replace("[", "").replace("]", "");
		if (!arrayString.contains(",")) {
			result.add(Integer.parseInt(arrayString));
		}
		String[] ids = arrayString.split(",");
		for (String id : ids) {
			int iId = Integer.parseInt(id);
			if (!result.contains(iId)) {
				result.add(iId);
			}
		}
		return result;
	}

	public static String sha1(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("sha1");
			messageDigest.update(str.getBytes());
			return byteArrayToHexString(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String md5(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("md5");
			messageDigest.update(str.getBytes());
			return byteArrayToHexString(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String byteArrayToHexString(byte[] b) {
		String result = "";
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}

	public static String base64(byte[] data) {
		return Base64.encodeBytes(data);
	}

	public static byte[] debase64(String data) {
		byte[] r = null;
		try {
			r = Base64.decode(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return r;
	}
}
